package scenic.study.arithmetic.stack;

import java.util.Iterator;

/**
 * Created by scenic on 2017/2/14.
 */
public class LinkedStack<T> implements StackInterface<T>{

    private Node first;
    private int N;
    @Override
    public boolean isEmpty() {
        return first == null;
    }

    @Override
    public int size() {
        return N;
    }

    @Override
    public T push(T o) {
        if(first == null){
            first = new Node();
            first.t = o;
        }else {
            Node oldFirst = first;
            first = new Node();
            first.t = o;
            first.next = oldFirst;
        }
        N++;
        return o;
    }

    @Override
    public T pop() {
        T result = first.t;

        Node oldFirst = first;
        first = first.next;
        oldFirst.next = null;
        oldFirst.t = null;
        N--;

        return result;
    }

    @Override
    public Iterator<T> iterator() {
        return new MyIterator();
    }

    class MyIterator implements Iterator<T> {

        Node first = LinkedStack.this.first;

        @Override
        public boolean hasNext() {
            return first != null;
        }

        @Override
        public T next() {
            Node node = first;
            first = first.next;
            return node.t;
        }
    }

    class Node {

        Node next;
        T t;
    }

}
